package com.liu.yuoj.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liu.yuoj.common.ErrorCode;
import com.liu.yuoj.constant.CommonConstant;
import com.liu.yuoj.exception.BusinessException;
import com.liu.yuoj.exception.ThrowUtils;
import com.liu.yuoj.judge.JudgeService;
import com.liu.yuoj.model.dto.questionsubmit.JudgeInfo;
import com.liu.yuoj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.liu.yuoj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.liu.yuoj.model.enums.JudgeInfoMessageEnum;
import com.liu.yuoj.model.enums.QuestionSubmitStatusEnum;
import com.liu.yuoj.model.entity.Question;
import com.liu.yuoj.model.entity.QuestionSubmit;
import com.liu.yuoj.model.entity.User;
import com.liu.yuoj.model.enums.QuestionSubmitLanguageEnum;
import com.liu.yuoj.model.vo.QuestionSubmitVO;
import com.liu.yuoj.model.vo.QuestionVO;
import com.liu.yuoj.model.vo.UserVO;
import com.liu.yuoj.service.QuestionService;
import com.liu.yuoj.service.QuestionSubmitService;
import com.liu.yuoj.mapper.QuestionSubmitMapper;
import com.liu.yuoj.service.UserService;
import com.liu.yuoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【question_submit(题目提交表)】的数据库操作Service实现
* @createDate 2025-01-13 20:49:45
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService{

    @Resource
    @Lazy
    private QuestionService questionService;

    @Resource
    private JudgeService judgeService;

    @Resource
    private UserService userService;

    //提交题目信息
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //校验参数
        if (questionSubmitAddRequest==null){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        //判断编程语言是否合法
        if (!QuestionSubmitLanguageEnum.getValues ().contains (questionSubmitAddRequest.getLanguage())){
            throw new BusinessException (ErrorCode.PARAMS_ERROR,"编程语言不合法!");
        }
        Long questionId = questionSubmitAddRequest.getQuestionId ();
        //查询题目是否存在
        Question question = questionService.getById (questionId);
        if (question==null){
            throw new BusinessException (ErrorCode.NOT_FOUND_ERROR);
        }
        //填充信息
        QuestionSubmit questionSubmit = new QuestionSubmit ();
        questionSubmit.setUserId (loginUser.getId ());
        BeanUtils.copyProperties (questionSubmitAddRequest, questionSubmit);
        questionSubmit.setJudgeInfo ("{}");
        //设置初始信息
        questionSubmit.setStatus (QuestionSubmitStatusEnum.WAITING.getValue());
        //保存结果
        int insert = this.baseMapper.insert (questionSubmit);
        ThrowUtils.throwIf (insert<0,ErrorCode.OPERATION_ERROR);
        //题目提交数+1
        question.setSubmitNum (Optional.ofNullable (question.getSubmitNum ()).orElse (0)+1);
        questionService.updateById (question);

        //执行判题(执行异步操作)
        CompletableFuture.runAsync (()->{
            judgeService.doJudge (questionSubmit.getId ());
        });

        return questionSubmit.getId ();
    }

    @Override
    public Wrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(),
                questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        //填充信息
        for (QuestionSubmitVO questionSubmitVO : questionSubmitVOList) {
            UserVO userVO = userService.getUserVO (userService.getById (questionSubmitVO.getUserId ()));
            questionSubmitVO.setUserVO (userVO);
            QuestionVO questionVO = questionService.getQuestionVO (questionService.getById (questionSubmitVO.getQuestionId ()));
            questionSubmitVO.setQuestionVO (questionVO);
        }
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

    private QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        if (questionSubmit==null){
            return null;
        }
        QuestionSubmitVO questionSubmitVO= QuestionSubmitVO.obToVo (questionSubmit);
        Long userId = loginUser.getId ();
        //仅管理员或者本人可以查看代码信息（这里有个小bug之前是userId ！= questionSubmit.getUserId()） 这样比较是错的
        if (!Objects.equals (userId, questionSubmit.getUserId ()) && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }
}




